<script setup>
import { ref,getCurrentInstance } from 'vue'
import { updateUser,addUser,queryUserById } from '@/api/user'
import { ElMessage } from 'element-plus'

//获取当前组件实例
const instance = getCurrentInstance()


//定义弹出框的数据
const title = ref(null)
const dialogShow = ref(false)
const dialogData = ref({userCode:'',name:'',username:'',role:'',gender:'',phone:'',status:''})

//添加或者修改用户信息
const saveUserInfo = async () => { 
  let result = null
  if(dialogData.value.id){
    //修改用户信息
    result = await updateUser(dialogData.value)
  }else{
    //添加用户信息
    result = await addUser(dialogData.value)
  }
  if(result.code){
    ElMessage.success('操作成功！')
    //关闭对话框
    dialogShow.value = false
    //重新加载数据
    instance.emit('search')
  }else{
    ElMessage.error('操作失败！请重新操作')
  }
}
const saveUserData = () => { 
  dialogShow.value = true
  title.value = '添加用户'
  //清空表单数据
  dialogData.value = {userCode:'',name:'',username:'',role:'',gender:'',phone:'',status:''}
}

//回显用户信息
const editUser = async (id) =>{
  dialogShow.value = true
  title.value = '修改用户'
  const result = await queryUserById(id)
  dialogData.value = result.data
}

// 暴露给父组件的变量和方法
defineExpose({
  title,
  dialogShow,
  dialogData,
  editUser,
  saveUserData
})
</script>

<template>
<!-- 弹出框 -->
  <el-dialog v-model="dialogShow" :title="title" width="500" align-center>
    <el-form :model="dialogData">
      <el-form-item label="编号" :label-width="formLabelWidth">
        <el-input v-model="dialogData.userCode" placeholder="请输入编号" />
      </el-form-item>
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="dialogData.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="账号" :label-width="formLabelWidth">
        <el-input v-model="dialogData.username" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="角色" :label-width="formLabelWidth">
        <el-input v-model="dialogData.role" placeholder="请输入角色" />
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth">
        <el-select v-model="dialogData.gender" placeholder="请选择">
          <el-option label="男" value="1"/>
          <el-option label="女" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="联系方式" :label-width="formLabelWidth">
        <el-input v-model="dialogData.phone" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="是否有效" prop="status">
        <el-switch v-model="dialogData.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogShow = false" type="default">取消</el-button>
      <el-button type="primary" @click="saveUserInfo">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>